package com.box.service.impl.luceneimpl;

import java.io.StringReader;
import java.nio.file.Paths;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.SimpleSpanFragmenter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.box.entity.DbBlog;
import com.box.service.lucene.BlogIndexService;
import com.box.utils.DateUtil;

@Service
public class BlogIndexServiceImpl implements BlogIndexService {
	
	@Value("${Directory}")
	private String Directory;
	
	private Directory  dir;
	
	/**
	 * 获取IndexWriter实例
	 * @return
	 * @throws Exception
	 */
	private IndexWriter getWriter()throws Exception{
		dir=FSDirectory.open(Paths.get(Directory));
		SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer();
		IndexWriterConfig iwc=new IndexWriterConfig(analyzer);
		IndexWriter writer=new IndexWriter(dir, iwc);
		return writer;
	}

	public Integer addIndexByBlog(DbBlog blog) throws Exception {
		// TODO Auto-generated method stub
		Integer n=0;
		try {	IndexWriter writer=getWriter();
		Document doc=new Document();
		//添加文档
		doc.add(new StringField("id",String.valueOf(blog.getId()),Field.Store.YES));
		System.out.println(blog.getId()+"................添加搜索id");
		doc.add(new TextField("title",blog.getTitle(),Field.Store.YES));
		doc.add(new TextField("summary", blog.getSummary(),Field.Store.YES));
		doc.add(new TextField("keyword", blog.getKeyword(),Field.Store.YES));
		doc.add(new TextField("imageUrl", blog.getImageurl(),Field.Store.YES));
		doc.add(new StringField("leaseDaet",DateUtil.formatDate(new Date(), "yyyy-MM-dd"),Field.Store.YES));
		doc.add(new TextField("content",blog.getContent(),Field.Store.YES));
		writer.addDocument(doc);
		writer.close();
			n=1;
			return n;
		} catch (Exception e) {
			// TODO: handle exception
			n=0;
			System.out.println("错误:"+e);
			return n;
		}
	

	}

	public Integer deleteIndexByBlog(String blogId) throws Exception {
		// TODO Auto-generated method stub
	Integer n=0;
		try {
			
			IndexWriter writer=getWriter();
			writer.deleteDocuments(new Term("id",blogId));
			writer.forceMergeDeletes(); // 强制删除
			writer.commit();
			writer.close();
			n=1;
			return n;
		} catch (Exception e) {
			// TODO: handle exception
			n=0;
			System.out.println("强制删除出错");
			return n;
		}
	

	}

	public Integer updateIndexByBlog(DbBlog blog) throws Exception {
		// TODO Auto-generated method stub
		Integer n=0;
		try {
			IndexWriter writer=getWriter();
			Document doc=new Document();
			doc.add(new StringField("id",String.valueOf(blog.getId()),Field.Store.YES));
			doc.add(new TextField("title",blog.getTitle(),Field.Store.YES));
			doc.add(new TextField("summary", blog.getSummary(),Field.Store.YES));
			doc.add(new TextField("keyword", blog.getKeyword(),Field.Store.YES));
			doc.add(new TextField("imageUrl", blog.getImageurl(),Field.Store.YES));
			doc.add(new StringField("releaseDate",DateUtil.formatDate(new Date(), "yyyy-MM-dd"),Field.Store.YES));
			doc.add(new TextField("content",blog.getContent(),Field.Store.YES));
			writer.updateDocument(new Term("id",String.valueOf(blog.getId())), doc);
			writer.close();
			n=1;
			return n;
		} catch (Exception e) {
			// TODO: handle exception
			n=0;
			System.out.println("更新博客索引出错:"+e);
			return n;
		}
	

	}

	public List<DbBlog> searchBlog(String q) throws Exception {
		// TODO Auto-generated method stub
		dir=FSDirectory.open(Paths.get(Directory));
		IndexReader reader=DirectoryReader.open(dir);
		IndexSearcher is=new IndexSearcher(reader);
		BooleanQuery.Builder booleanQuery=new BooleanQuery.Builder();
		SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer();
		QueryParser parser=new QueryParser("title", analyzer);
		Query query=parser.parse(q);
		
		QueryParser parser2=new QueryParser("content", analyzer);
		Query query2=parser2.parse(q);
		
		QueryParser parser3=new QueryParser("keyword", analyzer);
		Query query3=parser3.parse(q);
		
		QueryParser parser4=new QueryParser("imageUrl", analyzer);
		Query query4=parser4.parse(q);
		
		QueryParser parser5=new QueryParser("summary", analyzer);
		Query query5=parser5.parse(q);
	
		
		booleanQuery.add(query, BooleanClause.Occur.SHOULD);
		booleanQuery.add(query2, BooleanClause.Occur.SHOULD);
		booleanQuery.add(query3, BooleanClause.Occur.SHOULD);
		booleanQuery.add(query4, BooleanClause.Occur.SHOULD);
		booleanQuery.add(query5, BooleanClause.Occur.SHOULD);
		TopDocs hits=is.search(booleanQuery.build(), 100);
		QueryScorer scorer=new QueryScorer(query);
		Fragmenter fragmenter=new SimpleSpanFragmenter(scorer);
		SimpleHTMLFormatter simpleHTMLFormatter=new SimpleHTMLFormatter("<b><font color='red'>", "</font></b>");
		Highlighter highlighter=new Highlighter(simpleHTMLFormatter, scorer);
		highlighter.setTextFragmenter(fragmenter);
		
		List<DbBlog> blogList=new LinkedList<DbBlog>();
		for(ScoreDoc scoreDoc:hits.scoreDocs){
			Document doc=is.doc(scoreDoc.doc);
			DbBlog blog=new DbBlog();
			String id = doc.get("id");
			if(id!=null){
				int stringId = Integer.parseInt(id);
				System.out.println(stringId+"插入的id");
				blog.setId(stringId);	
			}
		
			String releaseDate = doc.get("leaseDaet");
		
			blog.setReleaseDateStr(releaseDate);
			String title=doc.get("title");
			String content=StringEscapeUtils.escapeHtml(doc.get("content"));
			String imageUrl=doc.get("imageUrl");
			String keyword=doc.get("keyword");
			String summary=doc.get("summary");
			if(title!=null){
				TokenStream tokenStream=analyzer.tokenStream("title", new StringReader(title));
				String hTitle=highlighter.getBestFragment(tokenStream, title);
				if(StringUtils.isEmpty(hTitle)){
					blog.setTitle(title);
				}else{
					blog.setTitle(hTitle);
				}
			}
			
			if(content!=null){
				TokenStream tokenStream=analyzer.tokenStream("content", new StringReader(content));
				String hContent=highlighter.getBestFragment(tokenStream, content);
				if(StringUtils.isEmpty(hContent)){
					if(content.length()<=200){
						blog.setContent(content);						
					}else{
						blog.setContent(content.substring(0, 200));	
					}
				}else{
					blog.setContent(hContent);
				}
			}
			
			
			if(imageUrl!=null){
		
				blog.setImageurl(imageUrl);
				
				
			}
			
			if(keyword!=null){
				TokenStream tokenStream=analyzer.tokenStream("keyword", new StringReader(keyword));
				String hkeyword=highlighter.getBestFragment(tokenStream, keyword);
				if(StringUtils.isEmpty(hkeyword)){
					if(hkeyword.length()<=200){
						blog.setKeyword(keyword);						
					}else{
						blog.setKeyword(keyword.substring(0, 200));	
					}
				}else{
					blog.setKeyword(hkeyword);
				}
				
			}
			
			if(summary!=null){
				TokenStream tokenStream=analyzer.tokenStream("summary", new StringReader(summary));
				String hsummary=highlighter.getBestFragment(tokenStream, summary);
				if(StringUtils.isEmpty(hsummary)){
					if(hsummary.length()<=200){
						blog.setSummary(summary);						
					}else{
						blog.setSummary(summary.substring(0, 200));	
					}
				}else{
					blog.setSummary(hsummary);
				}
				
			}
			blogList.add(blog);
		}
		return blogList;
	}

}
